<?php

class dbt_shake extends sing_table
{
    private $_G;
    private $_mid;
    private $_openid;
    private $_memberId;
    private $_shake; //活动数据
    private $_getData; //中奖数据
    private $_userData; //用户记录数据
    private $_prizeNum; //中奖数量
    private $_queueNum; //摇奖排队数量
    private $_redisWait; //等待对象
    private $_queueBtime;
    private $_queueEtime;

    //构造方法
    function __construct(){
        global $_G;
        $this->_G = &$_G;
        $this->_mid = $_GET['mid'];
        $this->_openid =  &$this->_G[$this->_mid]['openid'];
        $this->_memberId = &$this->_G[$this->_mid]['memberid'];

    }

    function __destruct() {
        if($this->_getData){
            $thisKey = "shakePrizeInsertBool-".$this->_shake['id']."-".$this->_getData['prize_key'];
            $queue = $this->redisWait();
            $queue->remove($thisKey ,$this->_memberId);
            $queue->rmWait($thisKey);
        }
    }

    //设置用户当前用户个人固定摇奖次数
    public function setUserFixedNum($num){
        $this->_userData['userFixedNum'] = intval($num);
        $this->userUpdate();
    }

    //用户数据修改
    public function userUpdate(){
        $thisUsr = $this->dataTurn($this->_userData);
        redis2("set","shakeUser-".$this->_memberId."-".$this->_shake['id'],$thisUsr);
    }

    //用户奖项类型的中奖数量
    public function userTypeNum($thisBool=false){
        if($thisBool){
            $this->_userData[$this->_getData['tabletype']] = intval($this->_userData[$this->_getData['tabletype']]) + 1;

            //某个奖品中奖数量key
            $prizecountKey = 'count-'.$this->_getData['tabletype']."-".$this->_getData['prize_key'];
            //缓存当前用户该奖品中奖数量
            if($this->_userData[$prizecountKey]){
                $this->_userData[$prizecountKey] = intval($this->_userData[$prizecountKey]) + 1;
            }else{
                $this->_userData[$prizecountKey] = 1;
            }
            $this->userUpdate();
        }else{
            $thisNum = $this->_userData[$this->_getData['tabletype']];
            return $thisNum;
        }
    }

    //用户奖项的中奖数量
    public function userPrizeNum($thisBool=false){
        if($thisBool){
            $this->_userData[$this->_getData['prize_key']] = intval($this->_userData[$this->_getData['prize_key']]) + 1;
            $this->userUpdate();
        }else{
            $thisNum = $this->_userData[$this->_getData['prize_key']];
            return $thisNum;
        }
    }

    //奖品中奖数量
    public function prizeNum($thisBool=false){
        if($thisBool){
            $thisNum = intval($this->_prizeNum) + 1;
            $thisNum = $this->dataTurn($thisNum);
            redis2("set","prizeNum-"."-".$this->_shake['id']."-".$this->_getData['prize_key'],$thisNum);
        }else{
            $thisNum = redis2("get","prizeNum-"."-".$this->_shake['id']."-".$this->_getData['prize_key']);
            if($thisNum){
                return $this->dataTurn($thisNum,"get");
            }else{
                return 0;
            }

        }
    }
    //获取默认奖品数据
    public function getPrizeKey($prizeArr=array(),$prizeKeyArr=array()){
        if(!$prizeArr || !is_array($prizeArr) || !$prizeKeyArr || !is_array($prizeKeyArr)){
            return false;
        }

        $lastArr = $prizeKeyArr;
        if($prizeKeyArr['count']!=-1){
            $this->_getData['prize_key'] = $prizeKeyArr['prize_key'];
            $thisNum = $this->prizeNum();
            if($prizeKeyArr['count'] <= intval($thisNum)){
                foreach($prizeArr as $thisArr){
                    if($thisArr['prize_key'] != $prizeKeyArr['prize_key']){
                        $this->_getData['prize_key'] = $thisArr['prize_key'];
                        $thisNum = $this->prizeNum();
                        if(intval($thisNum) < $thisArr['count']){
                            $lastArr = $thisArr;
                            break;
                        }
                    }
                }
            }
        }
        return $lastArr;
    }
    //插入用户摇奖总数量
    public function allCount($insert=array()){
        //当前活动总摇奖次数
        $this->_userData['allCount'] = intval($this->_userData['allCount']) + 1;

        //当用户当前的摇奖次数大于固定摇奖次数时，代表使用预售摇奖次数，记录+1
        if($this->_userData['allCount']>$this->_userData['userFixedNum']){
            //获取用户已用预售摇奖次数
            $userUsedAllNum = redis2("get","userUsedAllNum-".$this->_userData['memberid']);
            if($userUsedAllNum){
                $userUsedAllNum += 1;
            }else{
                $userUsedAllNum = 1;
            }
            redis2("set","userUsedAllNum-".$this->_userData['memberid'],$userUsedAllNum);
        }

        //如果用户中的是女王券，那么将插入用户中奖女王券到redis里，防止二次中奖
        if($this->_getData['tableid']==4729){
            redis2("set","queenpricecount-".$this->_userData['memberid'],$this->_userData['memberid']);
        }
//        $coupon= array(5552,5553,5554,5555,5556,5557,5558,5559,5560,5561,5562,5563,5564,5565,5566,5567,5568,5569,5570,5571,5572,5573,5574,5575,5576,5577,5578,5579,5580,5581,5582,5583,5584,5585,5586,5587,5588,5589,5590,5591,5592,5593,5594,5595,5596,5597,5598,5599,5600,5601,5602,5603,5604,5605,5606,5607,5608,5609,5610,5611,5612,5613,5614,5615,5616);
        $coupon= array(28,29,30,31);
        if(in_array($insert['tableid'], $coupon)){
            redis2("set","theFirstLovePrize-".$insert['shake_id']."-".$this->_userData['memberid'],$insert['shake_id']."-".$insert['tableid']);
        }
        $this->userUpdate();
    }

    //判断数量
    public function numInsertBool($lastData=array()){
        $userTypeNum = $this->userTypeNum();

        //判断当前《奖品类型》是否设置最大中奖数量，如果设置最大中奖数量，并且中奖达到数量，则返回未中奖信息
        if($this->_getData['typeNum']!=-1 && intval($userTypeNum)>=$this->_getData['typeNum']){

            return $this->noGetTip(-3);
        }

        //判断当前《奖品》是否设置最大中奖数量，如果设置最大中奖数量，并且中奖达到数量，则返回未中奖信息
        $prizecountKey = 'count-'.$this->_getData['tabletype']."-".$this->_getData['prize_key'];
        $prizecount = $this->_userData[$prizecountKey];
        if(!$prizecount){
            $prizecount = 0;
        }
        if($this->_getData['maxnum']!=-1 && intval($prizecount)>=$this->_getData['maxnum']){
            return $this->noGetTip(-11);
        }


        //判断当前奖品中奖数量，是否大于奖品设置的《奖品数量》
        $this->_prizeNum = $this->prizeNum();
        if($this->_getData['count']!=-1 && intval($this->_prizeNum)>=$this->_getData['count']){
            return $this->noGetTip(-4);
        }


        //如果当前中奖奖品为女王券并且用户已经中过女王券，那么返回中奖失败 女王券 tableid=4729
        if($this->_getData['tableid']==4729){
            $queen = redis2("get","queenpricecount-".$this->_userData['memberid']);
            if($queen){
                return $this->noGetTip(-12);
            }
        }
//        $coupon= array(5552,5553,5554,5555,5556,5557,5558,5559,5560,5561,5562,5563,5564,5565,5566,5567,5568,5569,5570,5571,5572,5573,5574,5575,5576,5577,5578,5579,5580,5581,5582,5583,5584,5585,5586,5587,5588,5589,5590,5591,5592,5593,5594,5595,5596,5597,5598,5599,5600,5601,5602,5603,5604,5605,5606,5607,5608,5609,5610,5611,5612,5613,5614,5615,5616);
        $coupon= array(28,29,30,31);
        if(in_array($lastData['tableid'], $coupon)){
            $queen = redis2("get","theFirstLovePrize-".$this->_shake['id']."-".$this->_userData['memberid']);
            if($queen){
                return $this->noGetTip(-12);
            }
        }


        //
        /*        $userPrizeNum = $this->userPrizeNum();
                if($this->_getData['maxnum']!=-1 && intval($userPrizeNum)>=$this->_getData['maxnum']){
                    return $this->noGetTip(-9);
                }*/
        return false;
    }

    //未中奖提示
    public function noGetTip($thisBool=false){
        $this->removeThisQueue();//当前用户退出队列

        if($this->_getData){
            $this->insertBool(1);
            if(in_array($thisBool,array(-6))){
                return array("Error"=>6001,"Msg"=>"很抱歉，系统繁忙，请重新摇奖","data"=>$this->_getData,"shake"=>$this->_shake,"thisBool"=>13,"thisGet"=>$thisBool);
            }
        }

        //此地为抽奖即使抽不中，也要算一次抽奖
        if($thisBool<=0){
            $this->allCount();
        }
        //        ddkddkdkdk

        //C::t('D')->WriteLogFile('shake1:$thisBool：'.$thisBool.",getData：". json_encode($this->_getData).",shake：". json_encode($this->_shake),'shaketrue.log','Debug');
        if($thisBool==1){
            return array("Error"=>6008,"Msg"=>"很抱歉，您未中奖","data"=>$this->_getData,"shake"=>$this->_shake,"thisBool"=>$thisBool);
        }
        if($thisBool==1){
            return array("Error"=>6010,"Msg"=>"很抱歉，不在活动时间！","data"=>$this->_getData,"shake"=>$this->_shake,"thisBool"=>$thisBool);
        }
        return array("Error"=>6001,"Msg"=>"很抱歉，您未中奖","data"=>$this->_getData,"shake"=>$this->_shake,"thisBool"=>$thisBool);
//        return array("Error"=>6001,"Msg"=>"很抱歉，您未中奖","thisBool"=>$thisBool);
    }

    //摇一摇中奖数据初始化
    public function shakeInit($thisData=array()){
        if(!$thisData){
            return $this->noGetTip(-5);
        }
        $this->_getData = $thisData;
    }

    //转换插入和读取的数据
    public function dataTurn($data="",$type="set"){
        if($type=="set"){
            if(is_array($data)){
                $lastData = "array|||".array2string($data);
            }else{
                $lastData = "string|||".$data;
            }
        }else if($type=="get"){
            if(is_array($data)){
                return $data;
            }
            $nowData = explode("|||", $data);
            if($nowData[0]=="array"){
                $lastData = string2array($nowData[1]);
            }else if($nowData[0]=="string"){
                $lastData = $nowData[1];
            }
        }
        return $lastData;
    }

    //redis 排队类
    public function redisWait(){
        $this->_redisWait = $this->_redisWait ? $this->_redisWait : new sing_queue();
        return $this->_redisWait;
    }

    //加入队列
    public function addQueue($queueNum = 0){
        $this->_queueNum = $queueNum;
        if(!$queueNum){
            return false;
        }
        $thisKey = "shakeQueueBool-".$this->_shake['id'];
        $queue = $this->redisWait();
        $limitNum = $queue->queue($thisKey, $this->_memberId, $queueNum , 3);
        if($limitNum>0)
        {
            $this->removeThisQueue();
            return array("Error"=>6001,"Msg"=>"很抱歉，系统繁忙，请重新摇奖","shake"=>$this->_shake,"thisBool"=>11);
        }

        return false;
    }

    //当前用户退出队列
    public function removeThisQueue(){
        if(!$this->_queueNum){
            return false;
        }
        $thisKey = "shakeQueueBool-".$this->_shake['id'];
        $queue = $this->redisWait();
        $queue->remove($thisKey ,$this->_memberId);
        $queue->rmWait($thisKey);
    }

    //插入状态
    public function insertBool($thisNum=0){

        $thisKey = "shakePrizeInsertBool-".$this->_shake['id']."-".$this->_getData['prize_key'];
        $queue = $this->redisWait();
        if($thisNum){
            $this->_queueEtime = microtime(true);
            $thisString = $this->dataTurn(array($this->_queueBtime,$this->_queueEtime,$this->_memberId,$this->_getData['prize_key']));
            $thisLogData = array($this->_queueBtime,$thisString);
            redis2("zadd","shake_queue_del-".$this->_shake['id'],$thisLogData);


            $queue->remove($thisKey ,$this->_memberId);
            $queue->rmWait($thisKey);
        }else{
            $limitNum = $queue->queue($thisKey, $this->_memberId, 1 , 1);
            if($limitNum>0)
            {
                $thisTime = microtime(true);
                $thisString = $this->dataTurn(array($thisTime,$this->_memberId,$this->_getData['prize_key']));
                $thisLogData = array($thisTime,$thisString);
                redis2("zadd","shake_false-".$this->_shake['id'],$thisLogData);
                $queue->remove($thisKey ,$this->_memberId);
                $queue->rmWait($thisKey);
                return $this->noGetTip(-6);
            }

            $this->_queueBtime = microtime(true);
            $thisString = $this->dataTurn(array($this->_queueBtime,$this->_memberId,$this->_getData['prize_key']));
            $thisLogData = array($this->_queueBtime,$thisString);
            redis2("zadd","shake_queue_add-".$this->_shake['id'],$thisLogData);
        }

        return false;


//        if($thisNum){
//            $thisNum = $thisNum==1?$this->_openid:0;
//            $thisBool = $this->dataTurn($thisNum);
//            redis2("set","shakeInsertBool-".$this->_shake['id']."-".$thisKey,$thisBool);
//            $thisOpenid = redis2("get","shakeInsertBool-".$this->_shake['id']."-".$thisKey);
//        }else{
//            $thisBool = redis2("get","shakeInsertBool-".$this->_shake['id']."-".$thisKey);
//            $thisBoolNow = $this->dataTurn($thisBool,"get");
//            if($thisBoolNow){
//                return C::t('#api#shake')->noGetTip(-6);
//            }else{
//                $this->insertBool(1); //中奖排队
//            }
//        }

//        $thisTime =TIME-10;
//        redis2("zremrangebyscore","shakeInsertBool1-".$this->_shake['id']."-".$thisKey,array(0,$thisTime));
//
//        if($thisNum){
//            $thisTime = microtime(true);
//            redis2("zremrangebyscore","shakeInsertBool1-".$this->_shake['id']."-".$thisKey,array(0,$thisTime));
//        }else{
//            $thisTime = microtime(true);
//            $thisString = $this->dataTurn($this->_openid);
//            $thisLogData = array($thisTime,$thisString);
//            redis2("zadd","shakeInsertBool1-".$this->_shake['id']."-".$thisKey,$thisLogData);
//
//            $data = redis2("zrange","shakeInsertBool1-".$this->_shake['id']."-".$thisKey,array(0,0));
//            if($data){
//                foreach($data as $thisArr){
//                    $thisArrNow = C::t("#shake#shake")->dataTurn($thisArr,"get");
//                    if($thisArrNow!=$this->_openid){
//                        return C::t('#api#shake')->noGetTip(-6);
//                    }
//                }
//            }
//        }

//        return $this->dataTurn($thisBool,"get");
    }

    //初始化微信用户数据
    public function shakeUser($thisBoll=false){ //allCount：已经摇奖数，yesgetNUm：中奖数
        if($thisBoll>0){
            $this->_shake['id'] = $thisBoll;
            $thisBoll = false;
        }
        $user = redis2("get","shakeUser-".$this->_memberId."-".$this->_shake['id']);
        $this->_userData = $this->dataTurn($user,"get");
        if(empty($user) || $thisBoll){//《用户不存在》或《活动进行中》
            DB::SetMainDB(DB_MAIN);
            $this->_userData = DB::fetch_first("select id as memberid,nickname,headimg,gid,number_other from %t where mid=%s and id=%s",array("common_member",$this->_mid,$this->_memberId));
            $this->_userData['loadTime'] = TIME;
            $this->_userData['shakeSendNum'] = 0;

            $userfimaly = DB::fetch_first("select isfam from %t where mid=%s and member_id=%s",array("common_member_perfect",$this->_mid,$this->_memberId));
            if($userfimaly){
                $this->_userData['isfam'] = $userfimaly['isfam'];//标记是否为家庭会员 0不是，1是
            }else{
                $this->_userData['isfam'] = 0;//标记是否为家庭会员 0不是，1是
            }
        }else if(empty($this->_userData['gid']) && (empty($this->_userData['loadTime']) || TIME-$this->_userData['loadTime']>60)){//《用户不存在会员等级》 且 《加载时间为空  或   加载时间超过60s》
            DB::SetMainDB(DB_MAIN);
            $thisUser = DB::fetch_first("select id as memberid,nickname,headimg,gid,number_other from %t where mid=%s and id=%s",array("common_member",$this->_mid,$this->_memberId));
            $this->_userData['nickname'] = $thisUser['nickname'];
            $this->_userData['headimg'] = $thisUser['headimg'];
            $this->_userData['gid'] = $thisUser['gid'];
            $this->_userData['loadTime'] = TIME;

            $userfimaly = DB::fetch_first("select isfam from %t where mid=%s and member_id=%s",array("common_member_perfect",$this->_mid,$this->_memberId));
            if($userfimaly){
                $this->_userData['isfam'] = $userfimaly['isfam'];//标记是否为家庭会员 0不是，1是
            }else{
                $this->_userData['isfam'] = 0;//标记是否为家庭会员 0不是，1是
            }
        }else if(empty($this->_userData['loadTime']) || TIME-$this->_userData['loadTime']>600){//《加载时间为空》  或   《加载时间超过600s》
            DB::SetMainDB(DB_MAIN);
            $thisUser = DB::fetch_first("select id as memberid,nickname,headimg,gid,number_other from %t where mid=%s and id=%s",array("common_member",$this->_mid,$this->_memberId));
            if($thisUser['gid'] && $thisUser['gid']!=$this->_userData['gid']){
                $this->_userData['gid'] = $thisUser['gid'];
                $this->_userData['loadTime'] = TIME;

                $userfimaly = DB::fetch_first("select isfam from %t where mid=%s and member_id=%s",array("common_member_perfect",$this->_mid,$this->_memberId));
                if($userfimaly){
                    $this->_userData['isfam'] = $userfimaly['isfam'];//标记是否为家庭会员 0不是，1是
                }else{
                    $this->_userData['isfam'] = 0;//标记是否为家庭会员 0不是，1是
                }
            }
        }
        //积分摇彩票计算次数
//        $member=$this->getMemberPoint();
//        if(!$this->_userData['point']){
//            $this->_userData['point']=$member['point'];
//            $this->_userData['pointNum'] = $member['num'];
//        }else{
//            if($this->_userData['point']!=$member['point']){
//                $this->_userData['point']=$member['point'];
//                $this->_userData['pointNum'] = $member['num'];
//            }
//        }
//        $user = $this->dataTurn($this->_userData);
//        redis2("set","shakeUser-".$this->_memberId."-".$this->_shake['id'],$user);
//        $this->getShakeSendNum();
        return $this->_userData;
    }
//20181229 抽奖中彩票 根据积分分配次数
    public function getMemberPoint(){
        DB::SetMainDB(DB_MAIN);
        $vipid = DB::result_first("select vid from %t where mid=%s and member_id=%s and display=1 and status=1",array("common_member_perfect",$this->_mid,$this->_memberId));
        $point = $this->getPointList($vipid);
        $num=floor($point/2000);
        $data['point']=$point;
        $data['num']=$num;
        return $data;
    }
    //获取增加的摇奖次数 - 获取redis次数增量，并且增加到shakeSendNum字段中
    public function getShakeSendNum(){
        if($this->_userData){
            $this->getYs();//获取剩余预售摇奖次数，添加到此次摇奖中

            $nowData = array();
            $befData = redis2("get","shakeSendNum-".$this->_userData['memberid']);
            if($befData){

                //记录用户预售的总次数
                $userAddAllNum = redis2("get","userAddAllNum-".$this->_userData['memberid']);
                if($userAddAllNum){
                    $userAddAllNum += intval($befData);
                }else{
                    $userAddAllNum = intval($befData);
                }


                //设置用户当前活动可用预售摇奖次数
                if($this->_userData['shakeSendNum']){
                    $this->_userData['shakeSendNum'] += intval($befData);
                }else{
                    $this->_userData['shakeSendNum'] = intval($befData);
                }



                redis2("set","userAddAllNum-".$this->_userData['memberid'],$userAddAllNum);//设置用户所有预售摇奖次数
                redis2("set","shakeSendNum-".$this->_userData['memberid'],0);
                $this->userUpdate();
                $this->_userData['test'] = "获取到数量 = ".$befData;
                $this->_userData['test1'] = "用户memberid ".$this->_userData['memberid'];
                $this->_userData['test2'] = "预售总次数 ".$userAddAllNum;
                $this->_userData['test3'] = "增加次数 ".$befData;
            }else{
                $this->_userData['test'] = "没获取到数量";
            }
        }else{
            $this->_userData['test'] = "没获取到用户数据";
        }
    }

    //获取剩余预售摇奖次数，添加到此次摇奖中
    public function getYs(){
        $curentAddFlag = redis2("get","currentaddflag-".$this->_userData['memberid']."-".$this->_shake['id']);
        if(!$curentAddFlag){
            //记录用户预售的总次数
            $userAddAllNum = redis2("get","userAddAllNum-".$this->_userData['memberid']);
            if($userAddAllNum){
                $userAddAllNum = intval($userAddAllNum);
            }else{
                $userAddAllNum = 0;
            }

            //获取用户已用预售摇奖次数
            $userUsedAllNum = redis2("get","userUsedAllNum-".$this->_userData['memberid']);
            if($userUsedAllNum){
                $userUsedAllNum = intval($userUsedAllNum);
            }else{
                $userUsedAllNum = 0;
            }

            $cz = $userAddAllNum - $userUsedAllNum;

            //设置用户当前活动可用预售摇奖次数
            if($this->_userData['shakeSendNum']){
                $this->_userData['shakeSendNum'] += intval($cz);
            }else{
                $this->_userData['shakeSendNum'] = intval($cz);
            }

            $this->userUpdate();//更新
            //当前活动已经添加预售
            redis2("set","currentaddflag-".$this->_userData['memberid']."-".$this->_shake['id'],1);//设置当前已添加到用户可用预售次数里
        }
    }

    //活动数据读取队列
    public function shakeGetBool($thisNum=0){
        if($thisNum){
            $thisNum = $thisNum==1?1:0;
            $thisBool = $this->dataTurn($thisNum);
            redis2("set","shakeGetBoolNew",$thisBool);
        }else{
            $thisBool = redis2("get","shakeGetBoolNew");
            $thisBoolNow = $this->dataTurn($thisBool,"get");
            if($thisBoolNow){
                return C::t('#api#shake')->noGetTip(6);
            }else{
                $this->shakeGetBool(1); //中奖排队
            }
        }

        return false;
    }

    //获取摇一摇数据
    public function getshake($thisBoll=false){

        $nowTime = TIME;

        $thisShake = redis2("get","getshake-".$this->_mid);
        $this->_shake = $thisShake?$this->dataTurn($thisShake,"get"):array();
        if(!$this->_shake || $this->_shake['etime']<$nowTime){
            $thisBoll = true;
        }


        if($thisBoll){
            $shakeGetBool = $this->shakeGetBool();
            if($shakeGetBool){
                return $shakeGetBool;
            }
            DB::SetMainDB(DB_ESHOP);
            $this->_shake = DB::fetch_first("select * from %t where display=1 and timetype=0 and etime>%d and mid=%s order by etime asc limit 1",array("es_shake",$nowTime,$this->_mid));
            $thisShake = $this->dataTurn($this->_shake);
            redis2("set","getshake-".$this->_mid,$thisShake);
            $this->shakeGetBool(2);
        }
        return $this->_shake;
    }

    //活动最大中奖基数
    public function shakeMaxNum($prize){

        $thisArr = redis2("get","shakeMaxNum-".$this->_shake['id']);
        if(!$thisArr){
            $pointNum = 2;
            foreach($prize as $pv){  //奖品中奖最大基数
                $arr = explode(".", $pv[' ']);
                $len = strlen($arr[1]);
                $pointNum = $pointNum>$len?$pointNum:$len;
            }
            $LastPow = pow(10,$pointNum);

            $maxNum = 100*$LastPow;

            $thisArr = array($maxNum,$LastPow);

            $thisMaxNum = $this->dataTurn($thisArr);

            redis2("set","shakeMaxNum-".$this->_shake['id'],$thisMaxNum);
        }else{
            $thisArr = $this->dataTurn($thisArr,"get");
        }

        return $thisArr;
    }

    //获取摇一摇优惠券数据
    public function getshakeCoupon($thisBoll=false){
        $thisCoupon = redis2("get","getshakeCoupon-".$this->_getData['tableid']);
        if(!$thisCoupon || $thisBoll){
            DB::SetMainDB(DB_ESHOP);
            $thisCoupon = DB::fetch_first("select * from %t where display=1 and id=%d and mid=%s",array("es_coupon",$this->_getData['tableid'],$this->_mid));
            $thisCoupon = $this->dataTurn($thisCoupon);
            redis2("set","getshakeCoupon-".$this->_getData['tableid'],$thisCoupon);
        }
        return $this->dataTurn($thisCoupon,"get");
    }

    //获取摇一摇代金券数据
    public function getCashCoupon($thisBoll=false){
        $thisCashCoupon = redis2("get","getCashCoupon-".$this->_getData['tableid']);
        if(!$thisCashCoupon || $thisBoll){
            DB::SetMainDB(DB_ESHOP);
            $thisCashCoupon = DB::fetch_first("select * from %t where display=1 and id=%d and mid=%s",array("es_cash_coupon",$this->_getData['tableid'],$this->_mid));
            $thisCashCoupon = $this->dataTurn($thisCashCoupon);
            redis2("set","getCashCoupon-".$this->_getData['tableid'],$thisCashCoupon);
        }
        return $this->dataTurn($thisCashCoupon,"get");
    }

    //获取摇一摇会员券数据
    public function getGroupCoupon($thisBoll=false){
        $thisGroupCoupon = redis2("get","getGroupCoupon-".$this->_getData['tableid']);
        if(!$thisGroupCoupon || $thisBoll){
            DB::SetMainDB(DB_ESHOP);
            $thisGroupCoupon = DB::fetch_first("select * from %t where display=1 and id=%d and mid=%s",array("es_group_coupon",$this->_getData['tableid'],$this->_mid));
            $thisGroupCoupon = $this->dataTurn($thisGroupCoupon);
            redis2("set","getGroupCoupon-".$this->_getData['tableid'],$thisGroupCoupon);
        }
        return $this->dataTurn($thisGroupCoupon,"get");
    }

    //获取摇一摇实物数据
    public function getThings($thisBoll=false){
        $thisThings = redis2("get","getThings-".$this->_getData['tableid']);
        if(!$thisThings || $thisBoll){
            DB::SetMainDB(DB_ESHOP);
            $thisThings = DB::fetch_first("select * from %t where display=1 and id=%d and mid=%s",array("es_things",$this->_getData['tableid'],$this->_mid));
            $thisThings = $this->dataTurn($thisThings);
            redis2("set","getThings-".$this->_getData['tableid'],$thisThings);
        }
        return $this->dataTurn($thisThings,"get");
    }

    //优惠券数据插入
    private function couponInsert(){
        $couponThis = $this->getshakeCoupon();
        if(!$couponThis || ($couponThis['btime'] && $couponThis['btime']>TIME) || ($couponThis['etime'] && $couponThis['etime']<TIME)){
            return $this->noGetTip(-7);
        }
        $insertArr = array();
        $insertArr['title'] = $couponThis['title'];
        $insertArr['description'] = $couponThis['description'];
        $insertArr['type'] = $couponThis['type'];
        $insertArr['group_id'] = $couponThis['group_id'];
        $insertArr['store_id'] = $couponThis['store_id'];
        $insertArr['thumb'] = $couponThis['thumb'];
        $insertArr['price'] = $couponThis['price'];
        $insertArr['limit_price'] = $couponThis['limit_price'];
        $insertArr['limit_user'] = $couponThis['limit_user'];
        $insertArr['btime'] = $couponThis['btime'];
        $insertArr['etime'] = $couponThis['etime'];
        $insertArr['limit_btime'] = $couponThis['limit_btime'];
        $insertArr['limit_etime'] = $couponThis['limit_etime'];
        $insertArr['isget'] = $couponThis['isget'];
        $insertArr['no_discount_group'] = $couponThis['no_discount_group'];
        $insertArr['limit_num'] = $couponThis['limit_num'];
        $insertArr['tagstr'] = $couponThis['tagstr'];
        $insertArr['is_activity'] = $couponThis['is_activity'];
        return $insertArr;
    }

    //代金券数据插入
    private function cashCouponInsert(){
        $cashCoupon = $this->getCashCoupon();
        if(!$cashCoupon || !$cashCoupon['coupon_stock_id']){
            return $this->noGetTip(-8);
        }
        $insertArr = array();
        $insertArr['title'] = $cashCoupon['title'];
        $insertArr['coupon_stock_id'] = $cashCoupon['coupon_stock_id'];
        $insertArr['intro'] = $cashCoupon['intro'];
        $insertArr['price'] = $cashCoupon['price'];
        return $insertArr;
    }

    //会员券数据插入
    private function groupCouponInsert(){
        $groupCoupon = $this->getgroupCoupon();
        if(!$groupCoupon){
            return $this->noGetTip(-9);
        }
        $insertArr = array();
        $insertArr['title'] = $groupCoupon['title'];
        $insertArr['intro'] = $groupCoupon['intro'];
        return $insertArr;
    }

    //实物数据插入
    private function thingsInsert(){
        $things = $this->getThings();
        if(!$things){
            return $this->noGetTip(-10);
        }
        $insertArr = array();
        $insertArr['title'] = $things['title'];
        $insertArr['intro'] = $things['intro'];
        $insertArr['overtime'] = $things['overtime'];
        return $insertArr;
    }

    //奖品信息插入
    public function shakePrize(){

        $returnArr = array();
        switch($this->_getData['tablename']){
            case 'es_coupon': //优惠券
                $returnArr = $this->couponInsert();
                break;
            case 'es_cash_coupon': //代金券
                $returnArr = $this->cashCouponInsert();
                break;
            case 'es_group_coupon': //会员券
                $returnArr = $this->groupCouponInsert();
                break;
            case 'es_things': //实物
                $returnArr = $this->thingsInsert();
                break;
        }

        return $returnArr;
    }
    //奖品是否还有
    public function shakePrizeAll(){
        foreach (json_decode($this->_shake['prize']) as $k=>$v){
            $p=$this->object_array($v);
            $thisNum = redis2("get","prizeNum-"."-".$this->_shake['id']."-".$p['prize_key']);
            $count[$k] = intval($p['count']);
            $num[$k] = intval($thisNum);
        }
        if($count[1]<=$num[1] && $count[2]<=$num[2] && $count[3]<=$num[3] && $count[4]<=$num[4] && $count[0]<=$num[0]){
            return $this->noGetTip(-4);
        }
        return false;

    }
    function object_array($array){
        if(is_object($array)){
            $array = (array)$array;
        }
        if(is_array($array)){
            foreach($array as $key=>$value){
                $array[$key] = $this->object_array($value);
            }
        }
        return $array;
    }
    //更新用户中记录
    public function updateOwmPrizeList($thisArr){
        if(!$thisArr || !is_array($thisArr)){
            return false;
        }
        $thisKey = "owmPrizeList-".$this->_memberId;
        $thisData = redis2("get",$thisKey);
        $thisObj = $this->dataTurn($thisData,"get");
        if(!$thisObj){
            $thisObj = array();
        }
        $thisObj[] = $thisArr;
        $thisData = $this->dataTurn($thisObj);
        redis2("set",$thisKey,$thisData);
    }

    //插入中奖记录
    public function allLogData($thisArr=array()){
        $thisTime = microtime(true);

        $thisString = $this->dataTurn($thisArr);
        $thisLogData = array($thisTime,$thisString);
        redis2("zadd","allLogData66",$thisLogData);
        redis2("zadd","allLogData77",$thisLogData);
        redis2("zadd","allLogData-".$thisArr['shake_id'],$thisLogData);

        $this->updateOwmPrizeList($thisArr);

        $nowArr = array("es_coupon1121","es_coupon1125","es_coupon1126","es_coupon1147","es_coupon1148","es_coupon1149","es_coupon1112","es_coupon1115","es_coupon1117","es_coupon1144","es_coupon1145","es_coupon1146"
        ,"es_coupon1119","es_coupon1122","es_coupon1123","es_coupon1126","es_coupon1131","es_coupon1133","es_coupon1135");
        if(!$nowArr || in_array($thisArr['tablename'].$thisArr['tableid'],$nowArr)){
            $thisArr['nickname'] = $this->_userData['nickname'];
            $thisArr['headimg'] = $this->_userData['headimg'];
            $thisArr['gid'] = $this->_userData['gid'];
            $thisString = $this->dataTurn($thisArr);
            $thisLogData = array($thisTime,$thisString);
            redis2("zadd","shake_screen",$thisLogData);
        }

        $this->insertBool(2); //取消中奖队列

        $this->removeThisQueue(); //移除当前队列
    }

    //插入摇一摇用户记录数据
    public function shakeInsert($insert=array()){

        $insert['inputtime'] = time();
        $insert['mid'] = $this->_mid;
        $insert['member_id'] = $this->_memberId;
        $insert['shake_id'] = $this->_shake['id'];

        $this->userTypeNum(true); //插入每人奖品类型中奖数量

        $this->prizeNum(true); //插入奖品中的数量

        $this->allCount($insert); //插入每人中奖总数量

        $this->allLogData($insert);//插入中奖记录
    }

    //查询表单信息
    public function getForm($tablename="",$id=0,$thisBoll=false){

        $thisData = redis2("get",$tablename."-".$id);
        if(!$thisData || $thisBoll){
            $thisData = C::t("#api#actPub")->form($tablename,$id);
            $thisData = $this->dataTurn($thisData);
            redis2("set",$tablename."-".$id,$thisData);
        }
        return $this->dataTurn($thisData,"get");

    }

    //添加表单信息
    public function addForm($mds="",$info=array()){
        if(!$mds){
            C::t("G")->rJson(array("Error"=>1,"Msg"=>"传输信息错误"));
        }

        if($info){
            $thisData = $this->dataTurn($info);
            redis2("set",$mds,$thisData);
        }else{
            $thisData = redis2("get",$mds);
        }

        return $this->dataTurn($thisData,"get");
    }




    /*//获取增加的摇奖次数   -   废弃
    public function getShakeSendNum(){

        $insertBool = false;
        if(!$this->_userData['unionid']){
            $insertBool = true;
            $thisR = $this->openid2unionid();
            if(array_key_exists("unionid",$thisR)){
                $this->_userData['unionid'] = $thisR['unionid'];
                $this->userUpdate();
            }else{
                $this->_userData = array();
                return false;
            }
        }

        if($this->_userData){
            $nowData = array();
            $befData = redis2("get","shakeSendNum-".$this->_userData['unionid']);
            if($befData){
                $nowData = $this->dataTurn($befData,"get");
                $thisArr = array();
                if($this->_userData['wxuserid']){
                    if($nowData['gid'] != $this->_userData['gid']){
                        $this->_userData['gid'] = $nowData['gid'];
                        $thisArr['gid'] = $nowData['gid'];
                        DB::SetMainDB(DB_MAIN);
                        DB::update("wx_wxuser", $thisArr, array("wxuserid"=>$this->_userData['wxuserid']));
                    }
                }else{
                    if($insertBool){
                        $this->_userData['gid'] = $nowData['gid'];
                        $thisArr['gid'] = $nowData['gid'];
                        $thisArr['unionid'] = $nowData['unionid'];
                        $thisArr['openid'] = $this->_openid;
                        $thisArr['mid'] = $this->_mid;
                        DB::SetMainDB(DB_MAIN);
                        DB::insert("wx_wxuser", $thisArr);
                    }else{
                        if($nowData['gid'] != $this->_userData['gid']){
                            $this->_userData['gid'] = $nowData['gid'];
                            $thisArr['gid'] = $nowData['gid'];
                            DB::SetMainDB(DB_MAIN);
                            DB::update("wx_wxuser", $thisArr, array("openid"=>$this->_openid,"mid"=>$this->_mid));
                        }
                    }
                }
                $this->_userData['shakeSendNum'] += intval($nowData['num']);
                redis2("set","shakeSendNum-".$this->_userData['unionid'],"");
                $this->userUpdate();
            }
        }
    }*/

    //根据openid获取unionid
    public function openid2unionid(){
        $accesstoken = active_check_access_token($this->_mid);
        $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$accesstoken.'&openid='.$this->_openid;
        $data = DoCurl($url);

        //C::t('D')->WriteLogFile('$data:'.$data,'openid2unionid.log','Debug');

        return json_decode($data,true);
    }
    function getPointList($vipid)
    {
        $result =  $this->getPoint($vipid);
        redis2("set","shakeUser-".$this->_memberId."-".$this->_shake['id']-"Point",$result);
        $result=intval($result['data']['integral']['OnlineAmtPoint'] + $result['data']['integral']['AmtPoint']);
        return $result;

    }
    private function getPoint($vipid)
    {
        $key_arr['vipid'] = $vipid;
        $point = $this->pullApiNew('getVipPoints',$key_arr,false);
        $xlConfig['onlineComCode']=array(80);
        if ($point['success']) {
            $integral = array(
                'OnlineAmtTotalPoint' => 0, // 线上成长值shakeUser
                'AmtTotalPoint' => 0, // 成长值
                'OnlineAmtTotalPoint1' => 0, // 线上累计积分
                'AmtTotalPoint1' => 0, // 累计积分
                'OnlineAmtPoint' => 0, // 线上积分
                'AmtPoint' => 0, // 积分

            );
            foreach (is_array($point['result']) ? $point['result'] : array() as $v) {
                if ($v['comCode'] && in_array($v['comCode'], $xlConfig['onlineComCode'])) {
                    $integral['OnlineAmtTotalPoint'] += $v['totalPoint'];
                    $integral['OnlineAmtTotalPoint1'] += $v['totalPoint1'];
                    $integral['OnlineAmtPoint'] += $v['point'];
                } else {
                    $integral['AmtTotalPoint'] += $v['totalPoint'];
                    $integral['AmtTotalPoint1'] += $v['totalPoint1'];
                    $integral['AmtPoint'] += $v['point'];
                }

            }
            return array('Error' => 0, 'data' => array('integral' => $integral), 'point' => $point);
        }
    }
    function pullApiNew($method, $param = array())
    {
        $url = 'http://v.xinglongdayuan.com/vip-service/shop/ProvisionalRegController/';
        $skey = 'F9CB0995-F80B-56D0-BCF5-8BBBDE1C1B75';
        $token= 'eyJhbGciOiJIUzI1NiJ8';
        $time = time();
        $sig = md5($token . intval(time()/1000) . $skey);
        $get = 'timestamp=' . $time . '&sig=' . $sig;
        $sendUrl = $url.$method . '?' .$get;
        if ($param && is_array($param)) {
            $str = '';
            foreach ($param as $k => $v) {
                if ($k == 'tstime') {
                    continue;
                }
                $str .= $k . '=' . $v . '&';
            }
            $str = trim($str, '&');
            $param = $str;
        }
        $jj = $sendUrl . '&' . $param;
        $DoCurl  = DoCurl($sendUrl, $param);
        $r = json_decode($DoCurl, true);
        return $r;
    }
    public function getshakeSendCoupon($thisBoll=false){
        $thisCoupon = redis2("get","getshakeCoupon-5547");
        if(!$thisCoupon || $thisBoll){
            DB::SetMainDB(DB_ESHOP);
            $thisCoupon = DB::fetch_first("select * from %t where display=1 and id=5547 and mid=%s",array("es_coupon",$this->_mid));
            $thisCoupon = $this->dataTurn($thisCoupon);
            redis2("set","getshakeCoupon-5547",$thisCoupon);
        }
        return $this->dataTurn($thisCoupon,"get");
    }
    //发送优惠券
    public function sendCoupon($thisArr=array()){
        if(!$thisArr){
            return false;
        }

        $couponLogArr = array();
        $couponLogArr['inputtime'] = time();
        $couponLogArr['mid'] = $thisArr['mid'];

        $couponLogArr['coupon_id'] = $thisArr['tableid'];
        $couponLogArr['openid'] = $thisArr['openid'];
        $couponLogArr['member_id'] = $thisArr['member_id'];
        $couponLogArr['gettype'] = 4;
        $couponLogArr['title'] = $thisArr['title'];

        $couponLogArr['store_id'] = $thisArr['store_id'];
        $couponLogArr['description'] = $thisArr['description'];
        $couponLogArr['thumb'] = $thisArr['thumb'];
        $couponLogArr['price'] = $thisArr['price'];
        $couponLogArr['limit_price'] = $thisArr['limit_price'];
        $couponLogArr['limit_user'] = $thisArr['limit_user'];
        $couponLogArr['btime'] = $thisArr['btime'];
        $couponLogArr['etime'] = $thisArr['etime'];
        $couponLogArr['limit_btime'] = $thisArr['limit_btime'];
        $couponLogArr['limit_etime'] = $thisArr['limit_etime'];
        $couponLogArr['no_discount_group'] = $thisArr['no_discount_group'];
        $couponLogArr['group_id'] = $thisArr['group_id'];
        $couponLogArr['type'] = $thisArr['type'];
        $couponLogArr['tagstr'] = $thisArr['tagstr'];
        $couponLogArr['is_activity'] = $thisArr['is_activity'];

        DB::SetMainDB(DB_ESHOP);
        $thisId = DB::insert("es_coupon_log", $couponLogArr,true);

        return $thisId;
    }

    //获取当前用户中奖信息
//    public function yetLog($openid="",$shakeId=0){
//        $openid = $openid?$openid:$this->_openid;
//
//        $thisUser = array();
//        $thisLogData = $this->allLogData();
//        if($thisLogData){
//            foreach($thisLogData as $thisData){
//                if($thisData['mid']==$this->_mid && $thisData['openid']==$openid && $thisData['yetget']==1){
//                    if(!$shakeId || $thisData['shake_id']!=$shakeId){
//                        $thisData['actInfo'] = "";
//                        if($thisData['tabletype']=="things"){
//                            $thisForm = $this->addForm();
//                            $thisData['actInfo'] = $thisForm?$thisForm:"";
//                        }
//                        $thisUser[] = $thisData;
//                    }
//                }
//            }
//        }
//
//        return $thisUser;
//    }
//
//

//
//    //初始化用户摇一摇数据
//    public function userInit(){
//        $thisUser = array();
//        $thisLogData = $this->_allLogData = $this->allLogData();
//        if($thisLogData){
//            foreach($thisLogData as $thisData){
//                if($thisData['mid']==$this->_mid && $thisData['openid']==$this->_openid && $thisData['shake_id']==$this->_shake['id']){
//                    $thisUser[] = $thisData;
//                }
//            }
//        }
//
//        $this->_userData = $thisUser;
//
//        return $thisUser;
//    }
//
//    //获取用户在活动中的记录
//    public function getThisUser($shakeId=0,$openid=""){
//
//        $openid = $openid?$openid:$this->_openid;
//
//        $thisUser = array();
//        $thisLogData = $this->allLogData();
//        if($thisLogData){
//            foreach($thisLogData as $thisData){
//                if($thisData['mid']==$this->_mid && $thisData['openid']==$openid && $thisData['shake_id']==$shakeId){
//                    $thisUser[] = $thisData;
//                }
//            }
//        }
//
//        return $thisUser;
//    }
//
//    //删除用户在活动中的记录
//    public function rmThisUser($shakeId=0,$openid=""){
//        $openid = $openid?$openid:$this->_openid;
//
//        $thisUser = array();
//        $thisLogData = $this->allLogData();
//        if($thisLogData){
//            foreach($thisLogData as $thisData){
//                if($thisData['mid']!=$this->_mid || $thisData['openid']!=$openid || $thisData['shake_id']!=$shakeId){
//                    $thisUser[] = $thisData;
//                }
//            }
//        }
//
//        $this->allLogData($thisUser);
//
//        return $thisUser;
//    }
}